<template>
    <!-- 卡片 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-button type="primary" :icon="Plus" @click="addTrademark">添加</el-button>
        </template>
        <!-- 表格 -->
        <el-table :data="tableData" border stripe style="margin-bottom: 30px">
            <el-table-column align="center" type="index" label="序号" width="80" />
            <el-table-column prop="tmName" label="品牌名称" ></el-table-column>
            <el-table-column prop="logoUrl" label="品牌LOGO">
                <template #default="{row}">
                    <img :src="row.logoUrl" height="80"/>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{row}">
                    <el-button type="warning" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
                    <el-button type="danger" :icon="DeleteFilled" @click="deleteTrademark(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="limit"
            :page-count="7"
            :total="total"
            :page-sizes="[3, 5, 7, 10]"
            layout="prev, pager, next , sizes , total"
        />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id? '修改商品' : '添加商品' ">
        <el-form label-width="100px" :model="newTrademark" :rules="rules" ref="fromEle">
        <el-form-item label="品牌名称" prop="tmName">
            <el-input autocomplete="off" v-model="newTrademark.tmName"/>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
            <!-- 上传 -->
            <el-upload
                class="avatar-uploader"
                :action="`${baseUrl}/admin/product/upload`"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
                <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="updateOrAddTrademark">确定</el-button>
        </span>
        </template>
    </el-dialog>
    
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Trademark",
});
</script>

<script setup lang="ts"> 
import {Plus , Edit , DeleteFilled} from "@element-plus/icons-vue"
import {ref , toRefs , onMounted , watch , reactive} from "vue"
import type {reqTrademarkReturnRecordsType , reqTrademarkReturnItemType} from "@/api/tradmark"
import {requestTrademarkList , requestUpdateTrademark , requestAddTrademark , requestDeleteTrademark} from "@/api/tradmark"
import { ElMessage , ElMessageBox} from 'element-plus'
import type { UploadProps , FormRules , FormInstance} from 'element-plus'

//1.表格逻辑
//定义表格需要的数据
const tableData = ref<reqTrademarkReturnRecordsType>([])

//2.页码逻辑
//页码的数据类型
interface pageDateType {
    page: number,
    limit: number,
    total: number,
}
//定义页码数据
const pageDate = ref<pageDateType>({
    page: 1,
    limit: 3,
    total: 100
})
//解构页码数据
const {page , limit , total} = toRefs(pageDate.value)

//3.获取商品列表
const getTrademarkList = async () => {
    //发送请求
    const result = await requestTrademarkList({page: page.value , limit:limit.value})
    //把表格需要的数据给表格
    tableData.value = result.records
    //把总页数给数据
    total.value = result.total
}
//初始化请求商品列表
onMounted(() => {
    getTrademarkList()
});
//监听页码数据的改变重新发送请求
watch([page , limit] , () => {
    getTrademarkList()
})

//4.弹窗逻辑
//定义数据控制弹窗的显示隐藏
const dialogFormVisible = ref(false)
//拿到路径前缀
const baseUrl = import.meta.env.VITE_API_URL
//定义要添加的一条数据
const newTrademark = ref<reqTrademarkReturnItemType>({
    id: 0,
    tmName: "",
    logoUrl: ""
})
//上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //把上传成功返回的图片地址给到数据
  newTrademark.value.logoUrl = response.data
  //有图片之后把校验图片的错误信息清空
  fromEle.value?.clearValidate("logoUrl")
}
//上传之前的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//5.点击添加的回调
const addTrademark = () => {
    //添加之前清空表单校验的错误信息
    fromEle.value?.clearValidate()
    //显示弹窗
    dialogFormVisible.value = true
    //清空弹窗内容
    newTrademark.value = {
        id: 0,
        tmName: "",
        logoUrl: ""
    }
}

//6.点击修改的回调
const updateTrademark = (row: reqTrademarkReturnItemType) => {
    //修改之前清空表单校验的错误信息
    fromEle.value?.clearValidate()
    //显示弹窗
    dialogFormVisible.value = true
    //获取到数据填入弹窗
    newTrademark.value = {...row}
}

//7.修改或新增商品
//拿到表单实例
const fromEle = ref<FormInstance>()
const updateOrAddTrademark = async () => {
    fromEle.value?.validate()
    .then(async ()=>{
        //点击关闭弹窗
        dialogFormVisible.value = false
        try {
            //判断是新增还是修改
            if(newTrademark.value.id){
                //修改商品
                await requestUpdateTrademark(newTrademark.value)
                ElMessage.success("修改成功")
            }else{
                //新增商品
                await requestAddTrademark(newTrademark.value)
                ElMessage.success("添加成功")
                //添加成功默认到第一页
                page.value = 1
            }
            //不管是添加成功还是修改成功都重新请求商品列表
            getTrademarkList()
        } catch (error) {
            //请求错误提示
            ElMessage.error(newTrademark.value.id? '修改错误' : '添加错误' )
        }
    })
    .catch(()=>{
        //表单校验失败提示
        ElMessage.error("表单校验失败!")
    })

    
}

//8.点击删除的回调
const deleteTrademark = async (id: number) => {
    //点击弹出确认取消框
    ElMessageBox.confirm('你确定要删除吗?','警告O-o',
        {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        }
    )  
    .then( async () => {
        //点击确定就执行删除逻辑
        try {
            await requestDeleteTrademark(id)
            //删除成功提示
            ElMessage.success("删除商品成功!")
            //重新请求商品列表
            getTrademarkList()
        } catch (error) {
            //删除失败提示
            ElMessage.error("删除商品信息失败!")
        }
    })
    .catch(() => {
        //点击取消提示
        ElMessage.error("取消成功!")
    })
}

//自定义表单规则
const mayRules = (rule: any, value: string, callback: any) => {
    //判断输入的内容在2-6位之间
    if(value.length < 2 || value.length > 5){
        callback("输入的长度不符合我的规则")
    }else{
        callback()
    }
}
//9.表单校验规则
const rules = reactive<FormRules>({
    tmName:[
        { required: true, message: '输入内容能为空', trigger: 'blur' },
        { validator: mayRules ,  trigger: 'blur' },
    ],
    logoUrl:[
        { required: true, message: '输入内容能为空'},
    ],
})

</script>

<style scoped>
    .avatar-uploader .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>
    
<style>
    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    
    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
</style>